<?php

namespace App\Http\Controllers\Web;

use App\Caches\WanSdkStartQueryCache;
use App\Caches\WechatOauthCodeCache;
use App\Http\Controllers\Controller;
use App\Models\Channels;
use App\Models\GameLoginConfig;
use App\Models\Games;
use App\Models\Orders;
use App\Services\GameChannelService;
use App\Services\GameLoginService;
use App\Services\WanSdk\WanSdkPayService;
use App\Services\WanSdk\WanSdkService;
use App\Services\WechatApi\WechatApiOauth;
use Illuminate\Http\Request;
use YQ\YqExtend;

class WanSdkController extends Controller
{
    // manifest.json
    public function manifest(Request $request, $game_id, $game_channel_id)
    {
        $game = Games::where('game_id', $game_id)->first();
        $game_channel = GameChannelService::getInstance()->get($game_channel_id, true);
        if ($game_channel) {
            $game_name = $game_channel->name;
        } else {
            $game_name = $game->game_name;
        }
        $game_url = WanSdkService::getInstance()->getGameUrl($game_id, $game_channel_id);
        $game_icon = $game->icon_url;
        $query_str = http_build_query($request->all());

        $data = [
            'name'        => $game_name,
            'short_name'  => $game_name,
            'start_url'   => "{$game_url}?{$query_str}",
            'scope'       => $game_url,
            'display'     => 'standalone',
            'orientation' => 'portrait',
            'icons'=> [
                [
                  'src'   => $game_icon,
                  'sizes' => '512x512',
                  'type'  => 'image/png'
                ]
            ],
        ];

        return response(json_encode($data, JSON_UNESCAPED_UNICODE), 200)
        ->header('Content-Type', 'application/json;charset=UTF-8');
    }

    // ab面切换，方便提审
    public function abIndex(Request $request, $game_id)
    {
        if ($game_id==1005) {
            return $this->index($request, $game_id);
        }
    }

    // 入口
    public function index(Request $request, $game_id, $game_channel_id = 0)
    {
        $params                    = $request->all();
        $channel                   = Channels::CHANNEL_H5;
        $game_channel_id           = GameChannelService::getInstance()->checkAndGetId($game_id, $channel, $game_channel_id);
        $params['game_channel_id'] = $game_channel_id;

        // 缓存外部透传的query
        $cache_id = YqExtend::uniqid32();
        WanSdkStartQueryCache::getInstance()->update($cache_id, $params);

        // 如果是微信，则唤起公众号登录
        $iswechat = WanSdkService::getInstance()->isWechatUa();
        if ($iswechat) {
            $url = WanSdkService::getInstance()->getWechatOauthUrl($game_id, $game_channel_id, ['cache_id' => $cache_id]);
            return redirect()->away($url);
        }

        // 如果是普通浏览器，则直接唤起登录页面
        return $this->oauthCb($request, $game_id, $cache_id);
    }

    // 唤起登录
    public function oauthCb(Request $request, $game_id = 0, $cache_id = '', $openid = '')
    {
        if ($game_id === 0) {
            $game_id = $request->input('game_id');
        }

        if (empty($cache_id)) {
            $cache_id = $request->input('cache_id') ?? '';
        }

        $query = WanSdkStartQueryCache::getInstance()->get($cache_id);
        if (empty($query)) {
            $query = [];
        }
        if (!isset($query['device_type'])) {
            $query['device_type'] = WanSdkService::getInstance()->getPhoneType();
        }

        $channel = Channels::CHANNEL_H5;
        $game    = Games::where('game_id', $game_id)->first();
        if (!$game) {
            return;
        }
        $game = $game->toArray();

        $game_channel_id = $query['game_channel_id'] ?? 0;
        $game_channel    = GameChannelService::getInstance()->checkAndGet($game_id, $channel, $game_channel_id);
        $game_channel_id = $game_channel['id'];

        // 是否手机端
        $is_phone = WanSdkService::getInstance()->isPhone()==true?1:0;

        // 公众号用户openid
        $code = $request->input('code') ?? '';
        if (empty($openid) && !empty($code)) {
            $res = WanSdkService::getInstance()->getWechatOffiaccountInfo($game_id, $game_channel_id, $code);
            // 如果授权失败，则判断code是否存在缓存中，如果是则认为玩家是通过刷新页面进来的
            if (empty($res)) {
                $info = WechatOauthCodeCache::getInstance()->get($code);
                if (!empty($info)) {
                    // 手机端 重新引导玩家进行授权登录
                    if ($is_phone == 1) {
                        WechatOauthCodeCache::getInstance()->forget($code);
                        $url = WanSdkService::getInstance()->getWechatOauthUrl($game_id, $game_channel_id, ['cache_id' => $cache_id]);
                        return redirect()->away($url);
                    // 电脑端 沿用旧openid
                    } else {
                        $openid = $info;
                    }
                }
            } else {
                $openid = $res['openid'];
                WechatOauthCodeCache::getInstance()->update($code, $openid);
            }
        }

        // 小程序用户openid
        $wx_openid = $query['wxopenid'] ?? '';

        // 是否微信
        $is_wechat = 0;
        if (!empty($openid)) {
            $is_wechat = 1;
        }
        // 是否小程序
        $is_minigame = 0;
        if (!empty($wx_openid)) {
            $is_minigame = 1;
        }

        $game_login_config = GameLoginService::getInstance()->get($game_id);
        return view('h5sdk.index', [
            'game'              => $game,
            'game_channel'      => $game_channel,
            'game_login_config' => $game_login_config,
            'openid'            => $openid,
            'wx_openid'         => $wx_openid,
            'query'             => $query,
            'is_wechat'         => $is_wechat,
            'is_minigame'       => $is_minigame,
            'is_phone'          => $is_phone,
            'manifest_url'      => WanSdkService::getInstance()->getManifestUrl($game_id, $game_channel_id, $query),
        ]);
    }

    /**
     * 用户点击公众号按钮或链接进行支付
     * 我们先进行授权拿到他的openid，然后查看他最近的创建的一笔订单进行付费
     *
     * @param Request $request
     * @param string $appid 公众号appid
     * @return void
     */
    public function clickWxpayJssdk(Request $request, $appid)
    {
        $cb_url = config('app.url') . "/h5sdk/wxpay_jssdk_access_token?appid={$appid}";
        $url = WechatApiOauth::getInstance()->getUserOauthUrl($appid, $cb_url, 'snsapi_base', 'pay');

        return redirect()->away($url);
    }

    // 基于微信公众号支付，调起授权成功返回获取openid
    public function wxpayJssdkAccessToken(Request $request)
    {
        $appid = $request->input('appid') ?? '';
        $code = $request->input('code') ?? '';
        $order = 9999;
        if (!empty($appid) && !empty($code)) {
            $order = WanSdkPayService::getInstance()->getOrderByJssdkAccessToken($appid, $code);
        }

        if (is_numeric($order)) {
            return view('h5sdk.pay_fail', []);
        }

        $game = Games::where('game_id', $order->game_id)->first();
        return view('h5sdk.pay', [
            'order'        => $order,
            'pay_platform' => Orders::PAY_PLATFORM_WAN_WECHAT_JSSDK,
            'game'         => $game,
            'game_url'     => WanSdkService::getInstance()->getGameUrl($order->game_id, $order->game_channel_id),
        ]);
    }
}
